package com.coding365.consumer.util;


import com.coding365.consumer.filter.TPMonitorFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class TimeScheduleIn5Sec implements CommandLineRunner {


    @Autowired
    private TPMonitorFilter tpMonitorFilter;

    @Override
    public void run(String... args) {
        //启动定时调度器,每秒中增加计数器
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        service.scheduleWithFixedDelay(() ->{
            try {
                Map<String, List<Long>[]> methodCallTimeMap = TPMonitorFilter.getMethodCallTimeMap();
                //计算每个方法的TP90,TP99
                for (String key : methodCallTimeMap.keySet()){
                    int count = 0;
                    //该方法所有调用时间的队列
                    List<Long> allCallTimeQueue = new ArrayList<>();
                    List<Long>[] queue = methodCallTimeMap.get(key);
                    for (int i = 0; i < queue.length ;i ++){
                        List<Long> queueInSec = queue[i];
                        if (queueInSec != null){
                            for (int j = 0; j < queueInSec.size(); j++){
                                count++;
                                allCallTimeQueue.add(queueInSec.get(j));
                            }
                        }
                    }
                    //从小到到排序
                    allCallTimeQueue.sort((o1,o2)->{
                        if (o1 < o2){
                            return -1;
                        }else if (o1 > o2){
                            return 1;
                        }else {
                            return 0;
                        }
                    });

                    //求出TP90和TP99的时间
                    int indexTP90 = (int)(count * 0.9);
                    int indexTP99 = (int)(count * 0.99);

                    Long TP90 = allCallTimeQueue.get(indexTP90);
                    Long TP99 = allCallTimeQueue.get(indexTP99);
                    System.out.println("一分钟调用次数==>" + count);
                    System.out.println("indexTP90==>" + indexTP90);
                    System.out.println("indexTP99==>" + indexTP99);

                    System.out.println("一分钟调用次数==>" + count + " 方法==>" + key + " 的TP90(毫秒)为==> " + TP90 + " 的TP99(毫秒)为==> " + TP99);


                }
            }catch (Exception e){
                e.printStackTrace();
            }


        },10,5,TimeUnit.SECONDS);
    }
}
